﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.EFCore;
using K9Nano.Events.Entity;
using K9Nano.Runtime;
using K9Nano.Share.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

namespace K9Nano.EFCore
{
    /// <summary>
    /// 仅用于配合<see cref="IDesignTimeDbContextFactory"/>完成“dotnet ef”操作
    /// </summary>
    public class DesignDbContextHelper: IDbContextHelper
    {
        public DbContext DbContext { get; set; }
        public ISessionContext SessionContext { get; } = new NullSessionContext();
        public IGlobalFilterProvider GlobalFilterProvider { get; }
        public IEntityChangeReport EntityChangeReport { get; }
        public ISystemClock SystemClock { get; }
        public IEntityCacheFilter EntityCacheFilter { get; }
        public IEntityEventFilter EntityEventFilter { get; }
        public bool MultiTenancy { get; }
        public bool FiltersDisabled { get; set; }
        public bool SuppressAutoSetTenantId { get; set; }
        public bool EventsDisabled { get; set; }

        public void OnModelCreating(ModelBuilder modelBuilder)
        {
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                // Naming convention
                var entityBuilder = modelBuilder.Entity(entityType.Name);
                var currentTableName = entityBuilder.Metadata.GetTableName();
                entityBuilder.ToTable(GetConventionalTableName(currentTableName));
            }
        }

        public string GetConventionalTableName(string tableName)
        {
            return tableName.ToSingular().ToSnakeCase();
        }

        public void SetValueIfNull(EntityEntry entry, string key, object value)
        {
            throw new NotImplementedException();
        }

        public int SaveChanges(bool acceptAllChangesOnSuccess, Func<bool, int> baseSaveChanges)
        {
            throw new NotImplementedException();
        }

        public Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellation, Func<bool, CancellationToken, Task<int>> baseSaveChanges)
        {
            throw new NotImplementedException();
        }

        public IQueryable<TEntity> Queryable<TEntity>() where TEntity : class
        {
            throw new NotImplementedException();
        }
    }
}